package com.yuanfeng.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.TokenUtils;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.entity.OrderInvoiceAddressEntity;
import com.yuanfeng.order.feign.BaseServiceClient;
import com.yuanfeng.order.mapper.OrderInvoiceAddressMapper;
import com.yuanfeng.order.service.OrderInvoiceAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName OrderInvoiceAddressServiceImpl
 * @Description  发票地址管理表
 * @Author cyp
 * @Date 2023-07-04 14:05:35
 * @Version 1.0
 **/
@Service
public class OrderInvoiceAddressServiceImpl extends ServiceImpl<OrderInvoiceAddressMapper, OrderInvoiceAddressEntity>
        implements OrderInvoiceAddressService {

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Override
    public ResponseResult list(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if(null == userInfo){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        try {
            param.put("userId",userInfo.getUserId());
            //分页查询数据
            IPage<OrderInvoiceAddressEntity> page = this.baseMapper.list(new Query<OrderInvoiceAddressEntity>().getPage(param),param);
            List<OrderInvoiceAddressEntity> records = page.getRecords();
            for (OrderInvoiceAddressEntity record : records) {
                String completeAddress = baseServiceClient.getAddressString(record.getAddressProvince(),record.getAddressCity(),record.getAddressArea()).getData().toString();
                record.setPreCompleteAddress(completeAddress);
                completeAddress = completeAddress + record.getAddressDetail();
                record.setCompleteAddress(completeAddress);
            }
            return ResponseResult.success(PageUtils.getPage(page));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult add(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if(null == userInfo){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        try {
            param.put("userId",userInfo.getUserId());
            if (param.get("invoiceTmpId") == null) {
                Integer count = this.baseMapper.queryAddressTmpListCount(param);
                //地址模版大于10个无法添加
                if(null !=count && count >= 10){
                    return ResponseResult.fail(BizCodeEnume.INVOICE_ADDRESS_TEMPLATES_HAS_REACHED_THE_UPPER_LIMIT.getCode(),BizCodeEnume.INVOICE_ADDRESS_TEMPLATES_HAS_REACHED_THE_UPPER_LIMIT.getMsg());
                }
                int isDefault = (Integer) param.get("isDefault");
                //如果新插入的为默认配置，则将其他的配置isDefault置为0
                if (1 == isDefault) {
                    this.baseMapper.updateAddressDefault(param);
                }
                this.baseMapper.insertAddressTmp(param);
            } else {
                this.baseMapper.updateAddressTmp(param);
            }
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult deleteAddressTmp(Map<String, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = TokenUtils.checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            this.baseMapper.delete(new LambdaQueryWrapper<OrderInvoiceAddressEntity>()
                    .eq(OrderInvoiceAddressEntity::getUserId, param.get("userId").toString())
                    .eq(OrderInvoiceAddressEntity::getAddressId, param.get("addressId").toString()));
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }
}
